/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package checker.sdchecker.unit;

/**
 *
 * @author takeshi
 */
public class UnitFormatter {

    private static long[] TIME_UNITS = {1000, 60, 60, 60};
    private static String[] TIME_UNITS_SYMBOLS = {"ms", "s", "m", "h"};


    private static String[] SPEED_UNITS = {"b/s", "kb/s", "mb/s", "gb/s"};

    public static String formatTime(long timeMillis) {
        return formatTimeRecurse(timeMillis, 0, "");
    }

    private static String formatTimeRecurse(long time, int timeUnitIndex, String soFar) {
        if (time == 0L || timeUnitIndex == TIME_UNITS.length) {
            return soFar;
        }
        long localTime = time % TIME_UNITS[timeUnitIndex];
        long rem = time / TIME_UNITS[timeUnitIndex];
        return formatTimeRecurse(rem, timeUnitIndex + 1, localTime + TIME_UNITS_SYMBOLS[timeUnitIndex] + " " + soFar);
    }


    public static String formatSpeed(double bytesPerSecond) {
        return formatSpeedR(bytesPerSecond, 0);
    }

    private static String formatSpeedR(double bytes, int index) {
        if(bytes < 1024.0 || index == SPEED_UNITS.length - 1) {
            return String.format("%.2f", bytes) + SPEED_UNITS[index];
        }
        return formatSpeedR(bytes / 1024.0, index + 1);
    }
}
